package com.jyw.framework.web.controller;

import com.jyw.common.core.domain.AjaxResult;
import com.jyw.common.core.domain.CommonResult;
import com.jyw.common.core.domain.model.CacheVersion;
import com.jyw.common.core.page.TableDataInfo;
import com.jyw.system.utils.CacheVersionUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author 沈峻
 * @ClassName ResponseBodyAdvice
 * @Description 统一返回封装
 * @Date 2023/8/25 15:27
 **/
@RestControllerAdvice
public class ResBodyAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(body instanceof AjaxResult){
            CacheVersion version = CacheVersionUtils.getVersion();
            AjaxResult res = (AjaxResult) body;
            res.put("version",version);
            return res;
        } else if (body instanceof CommonResult) {
            CacheVersion version = CacheVersionUtils.getVersion();
            CommonResult res = (CommonResult) body;
            res.setVersion(version);
            return res;
        }else if (body instanceof TableDataInfo) {
            CacheVersion version = CacheVersionUtils.getVersion();
            TableDataInfo res = (TableDataInfo) body;
            res.setVersion(version);
            return res;
        }else{
            return body;
        }
    }
}
